<template>
    <view class="add-form-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header :title="isEdit ? '编辑植保记录' : '新增植保记录'"></page-header>

        <!-- 使用地块选择器组件 -->
        <land-selector
            ref="landSelector"
            @selection-change="handleLandSelectionChange"></land-selector>

        <!-- 使用条田选择器组件 -->
        <section-selector
            ref="sectionSelector"
            @areaChange="handleAreaChange"
            @usersChange="handleUsersChange"></section-selector>

        <view class="basic-info">
            <view class="section-title">地块信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                class="farm-form">
                <uni-forms-item label="施药面积" name="area" required>
                    <uni-easyinput
                        type="digit"
                        disabled
                        v-model="formData.area"
                        placeholder="请输入">
                        <template #right>
                            <text class="input-unit">亩</text>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="负责人" name="personInCharge" required>
                    <uni-easyinput
                        v-model="formData.personInCharge"
                        placeholder="请输入负责人姓名"
                        disabled></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="basic-info">
            <view class="section-title">施药信息</view>

            <uni-forms class="farm-form" label-position="top">
                <uni-forms-item label="施药时间" name="dateRange" required>
                    <uni-datetime-picker
                        type="daterange"
                        v-model="dateRange"
                        @change="handleDateRangeChange"
                        :clear-icon="false"
                        :border="false">
                        <view class="uni-date-picker-container">
                            <text :class="{ placeholder: !dateRangeText }">
                                {{ dateRangeText || '请选择施药时间' }}
                            </text>
                            <view class="date-icon">
                                <roc-icon-plus
                                    type="fas"
                                    name="calendar-alt"
                                    :size="18"
                                    color="#999"></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item label="植保类型" name="protectionType" required>
                    <view class="radio-group">
                        <view
                            v-for="type in protectionTypesData"
                            :key="type.value"
                            class="radio-item"
                            @click="formData.protectionType = type.value">
                            <view
                                class="radio-circle"
                                :class="{ active: formData.protectionType === type.value }">
                                <view
                                    class="radio-inner"
                                    v-if="formData.protectionType === type.value"></view>
                            </view>
                            <text class="radio-label">{{ type.text }}</text>
                        </view>
                    </view>
                </uni-forms-item>

                <uni-forms-item label="施药方式" name="applicationMethod" required>
                    <view class="radio-group">
                        <view
                            v-for="method in applicationMethodsData"
                            :key="method.value"
                            class="radio-item"
                            @click="formData.applicationMethod = method.value">
                            <view
                                class="radio-circle"
                                :class="{ active: formData.applicationMethod === method.value }">
                                <view
                                    class="radio-inner"
                                    v-if="formData.applicationMethod === method.value"></view>
                            </view>
                            <text class="radio-label">{{ method.text }}</text>
                        </view>
                    </view>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="basic-info">
            <view class="section-title">用药信息</view>

            <view v-for="(item, index) in formData.listSubtable" :key="index" class="medicine-item">
                <view class="medicine-header">
                    <!-- <text class="medicine-title">药品 {{index + 1}}</text> -->
                    <view v-if="index > 0" class="delete-btn" @click="removeMedicineItem(index)">
                        删除
                    </view>
                </view>

                <uni-forms class="farm-form" label-position="top">
                    <!-- <view>药品名称:{{typeof item.pesticideId}}+{{item.pesticideId}}+{{item.pesticideName}}+{{pesticideNamesData}}</view> -->
                    <uni-forms-item
                        label="药品名称"
                        :name="'listSubtable[' + index + '].pesticideId'"
                        required>
                        <uni-data-select
                            v-model="item.pesticideId"
                            :localdata="pesticideNamesData"
                            placeholder="请选择药品名称"></uni-data-select>
                    </uni-forms-item>

                    <uni-forms-item
                        label="药品描述"
                        :name="'listSubtable[' + index + '].pesticideDescription'">
                        <uni-easyinput
                            type="textarea"
                            v-model="item.pesticideDescription"
                            placeholder="请输入药品描述"
                            maxlength="200"></uni-easyinput>
                    </uni-forms-item>

                    <!-- <uni-forms-item label="稀释倍数" :name="'listSubtable['+index+'].dilutionFactor'">
            <uni-easyinput
              type="text"
              v-model="item.dilutionFactor"
              placeholder="请输入稀释倍数"
            ></uni-easyinput>
          </uni-forms-item> -->

                    <uni-forms-item
                        label="用药量"
                        :name="'listSubtable[' + index + '].dosage'"
                        required>
                        <view class="dosage-input-group">
                            <uni-easyinput
                                type="digit"
                                v-model="item.dosage"
                                placeholder="请输入用药量"
                                @change="handleDosageChange(index)">
                                <template #right>
                                    <text class="input-unit">{{ item.dosageUnit || 'Kg' }}</text>
                                </template>
                            </uni-easyinput>
                            <uni-data-select
                                v-model="item.dosageUnit"
                                :localdata="dosageUnitOptions"
                                placeholder="选择单位"
                                :clear="false"
                                @change="handleUnitChange(index, $event)"
                                class="unit-select"></uni-data-select>
                        </view>
                    </uni-forms-item>

                    <uni-forms-item
                        label="亩均用量"
                        :name="'listSubtable[' + index + '].dosagePerMu'">
                        <uni-easyinput
                            type="digit"
                            v-model="item.dosagePerMu"
                            placeholder="请输入亩均用量"
                            @change="handleDosagePerMuChange(index)">
                            <template #right>
                                <text class="input-unit">{{ item.dosageUnit || 'Kg' }}/亩</text>
                            </template>
                        </uni-easyinput>
                    </uni-forms-item>
                </uni-forms>
            </view>

            <view class="add-medicine-btn" @click="addMedicineItem">
                <text class="add-icon">+</text>
                <text>添加药品</text>
            </view>
        </view>

        <view class="basic-info">
            <view class="section-title">备注</view>

            <uni-forms class="farm-form">
                <uni-forms-item name="remark">
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.remark"
                        placeholder="请输入备注信息"
                        maxlength="200"></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">现场照片</view>

            <image-uploader ref="imageUploader" :images="formData.images" :maxCount="9" />
        </view>

        <view class="submit-btn-container">
            <view class="submit-btn" @click="submitForm">
                {{ isEdit ? '确认修改' : '确认提交' }}
            </view>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import LandSelector from '@/components/LandSelector/index.vue'
import SectionSelector from '@/components/SectionSelector/index.vue'
import ImageUploader from '@/components/ImageUploader/index.vue'
import { protection } from '@/utils/api/index.js'
import { formatDate, formatImages, getDefaultDateRange } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        LandSelector,
        SectionSelector,
        ImageUploader,
    },
    data() {
        const defaultDateRange = getDefaultDateRange()
        return {
            isEdit: false,
            editId: null,
            dateRange: defaultDateRange.dateRange,
            selectedLands: [],
            selectedSections: [],
            formData: {
                id: null,
                startDate: defaultDateRange.dateRange[0],
                endDate: defaultDateRange.dateRange[1],
                plotId: '',
                fieldId: '',
                area: '',
                images: [],
                protectionType: '',
                applicationMethod: '无人机',
                personInCharge: '',
                personInId: '',
                notes: '',
                remark: '',
                listSubtable: [
                    {
                        protectionId: null,
                        pesticideId: null,
                        pesticideName: '',
                        pesticideDescription: '',
                        dilutionFactor: '',
                        dosage: '',
                        dosageUnit: 'Kg',
                        dosagePerMu: '',
                    },
                ],
            },
            rules: {
                dateRange: {
                    rules: [{ required: true, errorMessage: '请选择施药时间' }],
                },
                area: {
                    rules: [
                        { required: true, errorMessage: '请输入植保面积' },
                        { format: 'number', errorMessage: '植保面积必须是数字' },
                    ],
                },
                protectionType: {
                    rules: [{ required: true, errorMessage: '请选择植保类型' }],
                },
                applicationMethod: {
                    rules: [{ required: true, errorMessage: '请选择施药方式' }],
                },
                personInCharge: {
                    rules: [{ required: true, errorMessage: '请输入负责人姓名' }],
                },
            },
            // 默认数据，当字典加载失败时使用
            protectionTypesData: [
                // { value: "1", text: "病害" },
                // { value: "2", text: "草害" },
                // { value: "3", text: "虫害" }
            ],
            applicationMethodsData: [
                // { value: "无人机", text: "无人机" },
                // { value: "农机", text: "农机" }
            ],
            pesticideNamesData: [
                // { value: "除草剂", text: "除草剂" },
                // { value: "杀虫剂", text: "杀虫剂" },
                // { value: "杀菌剂", text: "杀菌剂" }
            ],
            dosageUnitOptions: [
                { value: 'Kg', text: 'Kg' },
                { value: 'L', text: 'L' },
            ],
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
            userInfo: 'getUserInfo',
        }),

        // 日期范围显示文本
        dateRangeText() {
            if (
                this.dateRange &&
                this.dateRange.length === 2 &&
                this.dateRange[0] &&
                this.dateRange[1]
            ) {
                return `${this.dateRange[0]} 至 ${this.dateRange[1]}`
            }
            return ''
        },
    },
    onLoad(options) {
        // 获取字典数据
        this.loadDictData()
        // 判断是否为编辑模式
        if (options.id) {
            this.isEdit = true
            this.editId = options.id // 存储编辑ID
            this.fetchProtectionDetail(options.id)
        } else {
            // 设置默认的负责人和负责人ID
            console.log('用户信息', this.userInfo)
            this.formData.personInId = this.userInfo.id
            this.formData.personInCharge = this.userInfo.nickname
        }
    },
    methods: {
        ...mapActions(['getDictData']),

        // 处理日期范围变更
        handleDateRangeChange(e) {
            if (e && e.length === 2) {
                this.formData.startDate = e[0]
                this.formData.endDate = e[1]
            }
        },

        // 添加药品项
        addMedicineItem() {
            this.formData.listSubtable.push({
                protectionId: null,
                pesticideId: '',
                pesticideName: '',
                pesticideDescription: '',
                dilutionFactor: '',
                dosage: '',
                dosageUnit: 'Kg',
                dosagePerMu: '',
            })
        },

        // 删除药品项
        removeMedicineItem(index) {
            this.formData.listSubtable.splice(index, 1)
        },

        // 加载字典数据
        async loadDictData() {
            try {
                uni.showLoading({ title: '加载字典数据...' })

                // 加载植保类型字典
                await this.getDictData('pests_diseases_weeds_type')
                const protectionTypes = this.formatDictToSelectData('pests_diseases_weeds_type')
                console.log('加载植保类型字典11')
                if (protectionTypes && protectionTypes.length > 0) {
                    this.protectionTypesData = protectionTypes
                }

                // 加载施药方式字典
                await this.getDictData('application_method')
                const applicationMethods = this.formatDictToSelectData('application_method')
                if (applicationMethods && applicationMethods.length > 0) {
                    this.applicationMethodsData = applicationMethods
                }

                // 加载药品名称字典
                await this.getDictData('drug_type')
                const pesticideNames = this.formatDictToSelectData('drug_type')
                if (pesticideNames && pesticideNames.length > 0) {
                    this.pesticideNamesData = pesticideNames
                }

                uni.hideLoading()
            } catch (error) {
                console.error('加载字典数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载字典数据失败，使用默认值',
                    icon: 'none',
                })
                // 出错时使用默认值，已在data中定义
            }
        },

        // 将字典数据格式化为下拉选择框所需的格式
        formatDictToSelectData(dictType) {
            const dictList = this.getDictByType(dictType)
            return dictList.map((item) => ({
                value: item.value,
                text: item.label,
            }))
        },

        // 处理地块选择变更
        handleLandSelectionChange() {
            this.updateSelectedLands()
        },
        handleAreaChange(area) {
            this.formData.area = area
            // 当施药面积变化时，重新计算所有药品的亩均用量
            this.recalculateAllDosagePerMu()
        },
        handleUsersChange(users) {
            this.formData.personInId = users.map((item) => item.userId).join(',')
            this.formData.personInCharge = users.map((item) => item.userName).join(',')
        },

        // 重新计算所有药品的亩均用量
        recalculateAllDosagePerMu() {
            const area = parseFloat(this.formData.area)
            if (area && area > 0) {
                this.formData.listSubtable.forEach((item, index) => {
                    if (item.dosage) {
                        const dosage = parseFloat(item.dosage)
                        const dosagePerMu = (dosage / area).toFixed(2)
                        item.dosagePerMu = dosagePerMu
                    }
                })
            }
        },

        // 更新选中的地块数据
        updateSelectedLands() {
            if (this.$refs.landSelector) {
                this.selectedLands = this.$refs.landSelector.getSelectedLands()
                console.log('更新选中的地块:', this.selectedLands)

                // 当地块选择变化时，更新条田选择器
                if (this.$refs.sectionSelector) {
                    this.$refs.sectionSelector.setSelectedParcels(this.selectedLands)
                    // 更新选中的条田
                    this.updateSelectedSections()
                }
            }
        },

        // 更新选中的条田数据
        updateSelectedSections() {
            if (this.$refs.sectionSelector) {
                this.selectedSections = this.$refs.sectionSelector.getSelectedSections()
                console.log('更新选中的条田:', this.selectedSections)
            }
        },

        // 验证表单
        validateForm() {
            // 更新选中的地块和条田
            this.updateSelectedLands()
            this.updateSelectedSections()

            // 检查是否选择了地块
            if (!this.$refs.landSelector.validate()) {
                uni.showToast({
                    title: '请选择至少一个地块',
                    icon: 'none',
                })
                return false
            }

            // 检查是否选择了条田
            if (!this.$refs.sectionSelector.validate()) {
                uni.showToast({
                    title: '请选择至少一个条田',
                    icon: 'none',
                })
                return false
            }

            return true
        },

        // 获取植保记录详情
        async fetchProtectionDetail(id) {
            try {
                uni.showLoading({ title: '加载中...' })

                const res = await protection.getProtectionDetail(id)

                if (res.code === 0 && res.data) {
                    const detail = res.data

                    // 设置日期范围
                    let startDate, endDate
                    if (detail.startDate) {
                        startDate = detail.startDate
                        endDate = detail.endDate || detail.startDate
                    } else {
                        startDate = formatDate(new Date())
                        endDate = formatDate(new Date())
                    }

                    this.dateRange = [startDate, endDate]

                    // 填充表单数据
                    this.formData = {
                        id: detail.id,
                        startDate: startDate,
                        endDate: endDate,
                        plotId: detail.plotId,
                        fieldId: detail.fieldId,
                        area: detail.area ? detail.area.toString() : '',
                        images: formatImages(detail.image),
                        protectionType: detail.protectionType,
                        applicationMethod: detail.applicationMethod || '无人机',
                        personInCharge: detail.personInCharge || '',
                        personInId: detail.personInId || '',
                        notes: detail.notes,
                        remark: detail.remark,
                        listSubtable:
                            detail.listSubtable && detail.listSubtable.length > 0
                                ? detail.listSubtable.map((item) => {
                                      // 计算亩均用量
                                      let dosagePerMu = ''
                                      if (item.dosage && detail.area && detail.area > 0) {
                                          const dosage = parseFloat(item.dosage)
                                          const area = parseFloat(detail.area)
                                          dosagePerMu = (dosage / area).toFixed(2)
                                      }
                                      item.pesticideId = item.pesticideId + ''

                                      return {
                                          ...item,
                                          dosageUnit: item.dosageUnit || 'Kg',
                                          dosagePerMu: item.dosagePerMu || dosagePerMu,
                                      }
                                  })
                                : [
                                      {
                                          protectionId: detail.id,
                                          pesticideId: detail.pesticideId + '',
                                          pesticideName: detail.pesticideName,
                                          pesticideDescription: detail.pesticideDescription,
                                          dilutionFactor: detail.dilutionFactor,
                                          dosage: detail.dosage,
                                          dosageUnit: detail.dosageUnit || 'Kg',
                                          dosagePerMu:
                                              detail.dosagePerMu ||
                                              (detail.dosage && detail.area && detail.area > 0
                                                  ? (
                                                        parseFloat(detail.dosage) /
                                                        parseFloat(detail.area)
                                                    ).toFixed(2)
                                                  : ''),
                                      },
                                  ],
                    }

                    // 等待组件加载完成后，设置地块选择状态
                    this.$nextTick(() => {
                        // 确保组件已完全加载
                        setTimeout(() => {
                            // 设置地块选择器中选中的地块
                            if (this.$refs.landSelector && this.formData.plotId) {
                                this.$refs.landSelector.setSelectedLands(this.formData.plotId)
                                this.updateSelectedLands()

                                // 更新条田选择器的地块ID
                                if (this.$refs.sectionSelector) {
                                    this.$refs.sectionSelector.setSelectedParcels(
                                        this.selectedLands
                                    )

                                    // 设置条田选择状态
                                    if (this.formData.fieldId) {
                                        this.$refs.sectionSelector.setSelectedFields(
                                            this.formData.fieldId
                                        )
                                        this.updateSelectedSections()
                                    }
                                }
                            }
                        }, 1200)
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '获取植保记录详情失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('获取植保记录详情失败', error)
                uni.showToast({
                    title: '获取植保记录详情失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 提交表单
        submitForm() {
            console.log(this.formData)
            // 使用uni-forms的验证方法
            this.$refs.form
                .validate()
                .then((result) => {
                    console.log('验证结果')
                    console.log(result)
                    console.log(this.validateForm())
                    if (this.validateForm()) {
                        this.submitFormData()
                    }
                })
                .catch((errors) => {
                    console.log('表单错误信息：', errors)
                })
        },

        // 提交表单数据到服务器
        async submitFormData() {
            try {
                // 获取选中的地块和条田
                this.updateSelectedLands()
                this.updateSelectedSections()

                let plotId = this.selectedLands.map((item) => item.id)
                let fieldId = this.selectedSections.map((item) => item.id)

                let plotName = this.selectedLands.map((item) => item.name)
                let fieldName = this.selectedSections.map((item) => item.name)

                // 验证药品信息
                for (let i = 0; i < this.formData.listSubtable.length; i++) {
                    const item = this.formData.listSubtable[i]
                    if (!item.pesticideId) {
                        uni.showToast({
                            title: `请选择第${i + 1}个药品名称`,
                            icon: 'none',
                        })
                        return
                    }
                    if (!item.dosage) {
                        uni.showToast({
                            title: `请输入第${i + 1}个药品用量`,
                            icon: 'none',
                        })
                        return
                    }
                }

                // 从imageUploader组件获取最新的图片列表
                const imageList = this.$refs.imageUploader.getImageList()

                // 构建提交的数据对象
                const submitData = {
                    id: this.isEdit ? this.editId : undefined,
                    startDate: this.dateRange[0],
                    endDate: this.dateRange[1],
                    plotId: plotId?.join(','), // 地块ID
                    fieldId: fieldId?.join(','), // 条田ID
                    plotName: plotName?.join(','), // 地块名称
                    fieldName: fieldName?.join(','), // 条田名称
                    area: parseFloat(this.formData.area),
                    protectionType: this.formData.protectionType,
                    applicationMethod: this.formData.applicationMethod,
                    personInCharge: this.formData.personInCharge,
                    personInId: this.formData.personInId || '',
                    image: imageList.join(','), // 图片URL拼接
                    notes: this.formData.notes || '',
                    remark: this.formData.remark || '',
                    // 确保子表中的每个项都有protectionId
                    listSubtable: this.formData.listSubtable.map((item) => ({
                        pesticideId: item.pesticideId + '',
                        pesticideName: item.pesticideName,
                        pesticideDescription: item.pesticideDescription,
                        dilutionFactor: item.dilutionFactor,
                        dosage: item.dosage,
                        dosageUnit: item.dosageUnit,
                        dosagePerMu: item.dosagePerMu,
                    })),
                }

                uni.showLoading({
                    title: '提交中...',
                })

                // 调用API创建或更新植保记录
                let res
                if (this.isEdit) {
                    res = await protection.updateProtectionRecord(submitData)
                } else {
                    res = await protection.createProtectionRecord(submitData)
                }

                uni.hideLoading()

                if (res.code === 0) {
                    uni.showToast({
                        title: this.isEdit ? '修改成功' : '添加成功',
                        icon: 'success',
                        duration: 2000,
                        success: () => {
                            setTimeout(() => {
                                // 返回上一页并刷新
                                uni.navigateBack({
                                    delta: 1,
                                })
                            }, 1500)
                        },
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '操作失败',
                        icon: 'none',
                        duration: 2000,
                    })
                }
            } catch (error) {
                uni.hideLoading()
                console.error('提交数据失败:', error)
                uni.showToast({
                    title: '提交失败，请重试',
                    icon: 'none',
                    duration: 2000,
                })
            }
        },
        // 处理用药量变化，自动计算亩均用量
        handleDosageChange(index) {
            const item = this.formData.listSubtable[index]
            const area = parseFloat(this.formData.area)

            if (item.dosage && area && area > 0) {
                const dosage = parseFloat(item.dosage)
                const dosagePerMu = (dosage / area).toFixed(2)
                item.dosagePerMu = dosagePerMu
            } else {
                item.dosagePerMu = ''
            }
        },
        // 处理亩均用量变化，自动计算用药量
        handleDosagePerMuChange(index) {
            const item = this.formData.listSubtable[index]
            const area = parseFloat(this.formData.area)

            if (item.dosagePerMu && area && area > 0) {
                const dosagePerMu = parseFloat(item.dosagePerMu)
                const dosage = (dosagePerMu * area).toFixed(2)
                item.dosage = dosage
            } else {
                item.dosage = ''
            }
        },
        // 处理单位变化
        handleUnitChange(index, unit) {
            const item = this.formData.listSubtable[index]
            item.dosageUnit = unit
        },
    },
}
</script>

<style lang="scss">
.medicine-item {
    background-color: #f9f9f9;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
    padding: 20rpx;

    .medicine-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;

        .medicine-title {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
        }

        .delete-btn {
            color: #ff5a5f;
            font-size: 28rpx;
        }
    }
}

.add-medicine-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    margin-top: 20rpx;

    .add-icon {
        font-size: 32rpx;
        margin-right: 10rpx;
        color: #2e6140;
    }

    text {
        font-size: 28rpx;
        color: #2e6140;
    }
}

.dosage-input-group {
    display: flex;
    align-items: center;
    gap: 10rpx;
}

.unit-select {
    width: 120rpx;
    min-width: 120rpx;
    flex-grow: 0 !important;
}
</style>
